package com.atguigu4.Exercise;

import java.sql.PreparedStatement;
import java.util.Scanner;

import org.junit.Test;

import com.atguigu3.util.JDBCUtils;
import com.mysql.jdbc.Connection;

public class ExerciseTest1 {
	
	@Test
	public void test()
	{
		Scanner scan = new Scanner(System.in);
		System.out.print("请输入用户名：");
		String name = scan.next();
		System.out.print("请输入邮箱：");
		String email = scan.next();
		System.out.print("请输入生日：");
		String birth = scan.next();
		String sql = "insert into customers(name,email,birth) values(?,?,?)";
		int insertCount = update(sql,name,email,birth);
		if(insertCount>0)
		{
			System.out.println("添加成功");
		}
		else
		{
			System.out.println("添加失败");
		}
	}
	
	
	public int update(String sql,Object ...args)//sql中占位符的个数与可变形参的长度一样
	{
		Connection conn = null;
		PreparedStatement ps = null;
		try {
			//1.获取数据库的连接
			conn = JDBCUtils.getConnection();
			//2.预编译sql语句，返回perparedstatement的实例
			ps = (PreparedStatement) conn.prepareStatement(sql);
			//3.填充占位符
			for(int i=0;i<args.length;i++)
			{
				ps.setObject(i+1, args[i]);//小心参数声明错误
			}
			//4.执行
			/*
			 * ps.execute();
			 * 如果执行的是查询操作，有返回结果，则此方法返回true
			 * 如果执行的是增，删，改操作，没有返回结果，则此方法返回false
			 */
			//ps.execute();
			return ps.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			//5.关闭资源
			JDBCUtils.closeResource(conn, ps);
		}
		return 0;
	}

}
